package com.smartStatus.admin.controller;


import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.itextpdf.text.Image;
import com.smartStatus.admin.service.*;
import com.smartStatus.admin.utils.JoinUtil;
import com.smartStatus.api.entity.*;
import com.smartStatus.api.vo.SsyTenantVO;
import com.smartStatus.api.vo.SysStudentStatusVO;
import com.smartStatus.api.vo.TenantDepartmentVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.smartStatus.core.util.R;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户学籍表 Controller
 *
 * @author lby
 * @since 2021-03-06
 */
@RestController
@Slf4j
@Api(value = "SysStudentStatusController", tags = "SysStudentStatus管理")
@AllArgsConstructor
@RequestMapping("/SysStudentStatus")
public class SysStudentStatusController {

    private final SysStudentStatusService sysStudentStatusService;
    private final SysFileService sysFileService;
    private final TenantDepartmentService tenantDepartmentService;
    private final SysDepartmentService sysDepartmentService;
    private final SysMajorService sysMajorService;
    private final SysTenantService sysTenantService;
    private final SysUserService sysUserService;

    /**
     * 分页数据
     */
    @PreAuthorize("@pms.hasPermission('sys_studentStatus_view')")
    @ApiOperation(value = "公共参数分页数据")
    @GetMapping("/page")
    public R sysStudentStatusPage(Page<SysStudentStatus> page, SysStudentStatus sysStudentStatus) {
        QueryWrapper<SysStudentStatus> query = Wrappers.query();
        Page<SysStudentStatus> page1 = sysStudentStatusService.page(page, query);
        Page page2 = JoinUtil.page(page1, SysStudentStatusVO.class);
        List<SysStudentStatusVO> records = page2.getRecords();
        records.forEach(sysStudentStatusVO -> {
            SysUser byId = sysUserService.getById(sysStudentStatusVO.getUserId());
            if (byId != null) {
                SysTenant byId1 = sysTenantService.getById(sysStudentStatusVO.getTenantId());
                sysStudentStatusVO.setJobNumber(byId.getJobNumber());
                sysStudentStatusVO.setUserName(byId.getName());
                sysStudentStatusVO.setTenantName(byId1.getName());
            }
        });
        return R.ok(page2);
    }


    /**
     * 列表数据
     */
    @PreAuthorize("@pms.hasPermission('sys_studentStatus_view')")
    @ApiOperation(value = "公共参数列表")
    @GetMapping("/list")
    public R sysStudentStatusList() {
        return R.ok(sysStudentStatusService.list());
    }


    /**
     * 编辑数据
     */
    @PreAuthorize("@pms.hasPermission('sys_studentStatus_view')")
    @ApiOperation(value = "编辑公共参数")
    @ApiImplicitParam(name = "SysStudentStatus", value = "SysStudentStatus实体", required = true, dataType = "SysStudentStatus")
    @PutMapping("/edit")
    public R sysStudentStatusUpdate(@RequestBody SysStudentStatus sysStudentStatus) {
        return R.ok(sysStudentStatusService.updateById(sysStudentStatus));
    }


    /**
     * 删除数据
     */
    @PreAuthorize("@pms.hasPermission('sys_studentStatus_view')")
    @ApiOperation(value = "删除公共参数")
    @ApiImplicitParam(name = "id", value = "id", required = true, dataType = "Integer")
    @DeleteMapping("/{id}")
    public R sysStudentStatusDelete(@PathVariable Integer id) {
        return R.ok(sysStudentStatusService.removeById(id));
    }

    /**
     * 添加数据
     */
    @PreAuthorize("@pms.hasPermission('sys_studentStatus_view')")
    @ApiOperation(value = "添加公共参数")
    @ApiImplicitParam(name = "SysStudentStatus", value = "SysStudentStatus实体", required = true, dataType = "SysStudentStatus")
    @PostMapping("/add")
    public R sysStudentStatusInsert(@RequestBody SysStudentStatusVO sysStudentStatus) {
        QueryWrapper<SysUser> query = Wrappers.query();
        query.eq("id", sysStudentStatus.getUserName());
        SysUser one = sysUserService.getOne(query);
        if (one != null) {
            // 同一个人只能有一张学籍
            QueryWrapper<SysStudentStatus> query1 = Wrappers.query();
            query1.eq("user_id", one.getId());
            int count = sysStudentStatusService.count(query1);
            if (count > 0) {
                return R.failed("该用户已有学籍，请勿重复添加");
            }
            // 随机生成一个学籍号
            String number = String.valueOf(System.currentTimeMillis()).substring(1, 9);
            sysStudentStatus.setUserId(one.getId());
            sysStudentStatus.setNumber(number);
            return R.ok(sysStudentStatusService.save(sysStudentStatus));
        } else {
            return R.failed("该用户不存在");
        }
    }


    /**
     * 上传学籍照片
     *
     * @return
     */
    @PreAuthorize("@pms.hasPermission('sys_studentStatus_view')")
    @ApiOperation(value = "上传学籍照片")
    @PostMapping("/upload-education-image")
    public R uploadEducationImage(@RequestParam("file") MultipartFile multipartFile) {
        Map<String, String> map = sysFileService.uploadFile(multipartFile);
        if (map != null) {
            return R.ok(map, "上传成功");
        } else {
            return R.failed("上传失败");
        }
    }

    /**
     * 获取学校绑定的数据
     *
     * @param
     * @return
     */
    @PreAuthorize("@pms.hasPermission('sys_studentStatus_view')")
    @ApiOperation(value = "获取学校绑定的数据")
    @GetMapping("/get-department")
    public R getDepartments() {
        List<TenantDepartment> list = tenantDepartmentService.list();
        List<TenantDepartmentVO> list1 = JoinUtil.list(list, TenantDepartmentVO.class);
        if (list1.size() > 0) {
            list1.forEach(tenantDepartmentVO -> {
                SysDepartment byId = sysDepartmentService.getById(tenantDepartmentVO.getDepartmentId());
                SysMajor byId1 = sysMajorService.getById(tenantDepartmentVO.getMajorId());
                SysTenant byId2 = sysTenantService.getById(tenantDepartmentVO.getTenantId());
                tenantDepartmentVO.setDepartmentName(byId.getName());
                tenantDepartmentVO.setMajorName(byId1.getName());
                tenantDepartmentVO.setTenantName(byId2.getName());
            });
            return R.ok(list1);
        } else {
            return R.failed("未获取数据");
        }

    }

    /**
     * 条件获取
     *
     * @param id
     * @return
     */
    @PreAuthorize("@pms.hasPermission('sys_studentStatus_view')")
    @ApiOperation(value = "条件获取")
    @GetMapping("/get-by-id/{id}")
    public R getById(@PathVariable("id") Integer id) {
        return R.ok(sysStudentStatusService.getById(id));
    }


    /**
     * 导出学籍数据pdf
     *
     * @param statusVO
     * @return
     */
    @PreAuthorize("@pms.hasPermission('sys_studentStatus_view')")
    @ApiOperation(value = "导出学籍数据pdf")
    @PostMapping("/export-pdf")
    public void exportPdfData(@RequestBody SysStudentStatusVO statusVO, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<>();
        // 设置毕业年份
        Integer graduationYear = null;
        // 时间转换
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        SysUser byId = sysUserService.getById(statusVO.getUserId());
        SysTenant byId1 = sysTenantService.getById(statusVO.getTenantId());
        SysMajor byId2 = sysMajorService.getById(statusVO.getMajor());
        SysDepartment byId3 = sysDepartmentService.getById(statusVO.getDepartment());
        map.put("userName", statusVO.getUserName());
        if (byId.getSex() == 0) {
            map.put("sex", "男");
        } else {
            map.put("sex", "女");
        }
        map.put("birthday", df.format(byId.getBirthday()));
        map.put("famousFamily", byId.getFamousFamily());
        map.put("idCard", byId.getIdCard());
        map.put("tenantName", byId1.getName());
        map.put("education", statusVO.getEducation());
        map.put("major", byId2.getName());
        map.put("educationalSystem", statusVO.getEducationalSystem());
        map.put("learningForm", statusVO.getLearningForm());
        map.put("educationType", statusVO.getEducation());
        map.put("department", byId3.getName());
        map.put("class", "2017级3班");
        map.put("jobNumber", byId.getJobNumber());
        String currentTime = (statusVO.getAdmissionTime()).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        map.put("admissionTime", currentTime);
        if ("三年制".equals(statusVO.getEducationalSystem())) {
            graduationYear = statusVO.getAdmissionTime().getYear() + 3;
        } else if ("四年制".equals(statusVO.getEducationalSystem())) {
            graduationYear = statusVO.getAdmissionTime().getYear() + 4;
        } else if ("五年制".equals(statusVO.getEducationalSystem())) {
            graduationYear = statusVO.getAdmissionTime().getYear() + 5;
        } else if ("二年制".equals(statusVO.getEducationalSystem())) {
            graduationYear = statusVO.getAdmissionTime().getYear() + 2;
        }
        String graduationTime = graduationYear + "-06-31";
        map.put("gradurationTime", graduationTime);
        if (statusVO.getState() == 0) {
            map.put("state", "在籍");
        } else {
            map.put("state", "离校");
        }
        // 在pdf中插入图片
        if (statusVO.getPaperImage() != null) {
            map.put("imageUrl", statusVO.getPaperImage());
        }
        sysStudentStatusService.exportPdf(response, map);
    }
}
